import type {
  AICompletionRequest,
  AICompletionResponse,
  AICommentRequest,
  AICommentResponse,
  AICompletionServiceRequest,
  AICompletionServiceResponse,
  AICommentServiceRequest,
  AICommentServiceResponse
} from '../../dto/ai';

// AI相关API
export const aiApi = {
  // AI代码补全
  async chatOneAIGC(params: AICompletionRequest): Promise<AICompletionResponse> {
    try {
      console.log('API调用AI补全，参数:', params);

      const result = await getAICompletion({
        prefixContent: params.prefixContent,
        suffixContent: params.suffixContent,
        language: params.language
      });

      console.log('AI补全服务返回结果:', result);

      if (result.success) {
        return {
          code: 1,
          message: 'success',
          data: result.data
        };
      } else {
        return {
          code: 0,
          message: result.error || 'AI补全失败',
          data: []
        };
      }
    } catch (error) {
      console.error('AI补全服务调用失败:', error);
      return {
        code: 0,
        message: error instanceof Error ? error.message : 'Unknown error',
        data: []
      };
    }
  },

  // AI代码注释
  async getCodeComments(
    params: AICommentRequest,
    onStreamComment?: (comment: { lineNumber: number; comment: string }) => void
  ): Promise<AICommentResponse> {
    try {
      console.log('API调用AI代码注释，参数:', params);

      const result = await getAICodeComments({
        code: params.code,
        language: params.language
      }, onStreamComment);

      console.log('AI代码注释服务返回结果:', result);

      if (result.success) {
        return {
          code: 1,
          message: 'success',
          data: result.data
        };
      } else {
        return {
          code: 0,
          message: result.error || 'AI代码注释失败',
          data: []
        };
      }
    } catch (error) {
      console.error('AI代码注释服务调用失败:', error);
      return {
        code: 0,
        message: error instanceof Error ? error.message : 'Unknown error',
        data: []
      };
    }
  }
};

// AI服务实现函数
/**
 * 使用新的AI代码补全接口
 * @param request 补全请求参数
 * @returns 补全结果
 */
export async function getAICompletion(request: AICompletionServiceRequest): Promise<AICompletionServiceResponse> {
  try {
    const { prefixContent, suffixContent, language } = request;

    // 添加调试日志
    console.log('AI补全请求参数:', { language, prefixLength: prefixContent.length, suffixLength: suffixContent.length });

    // 构建请求URL（使用URL参数）
    const baseUrl = 'http://127.0.0.1:8080/api/ai/qwen/chat/completion';
    const params = new URLSearchParams({
      'prefix': prefixContent,
      'suffix': suffixContent,
      'language': language || "c++"
    });
    const url = `${baseUrl}?${params.toString()}`;

    console.log('请求URL:', url);

    // 发送GET请求
    const requestOptions = {
      method: 'GET',
      redirect: 'follow' as RequestRedirect
    };

    const response = await fetch(url, requestOptions);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    console.log('AI补全响应:', result);

    // 检查响应格式（适配新的API格式）
    if (result.code === 200 && result.message === '成功' && result.data) {
      const completionText = result.data;
      console.log('AI补全成功，返回结果:', completionText);

      if (completionText && isValidCompletion(completionText)) {
        return {
          success: true,
          data: [completionText]
        };
      } else {
        console.log('AI补全无效，原因: 内容为空或不符合条件');
      }
    } else {
      console.log('AI补全响应格式错误:', result);
      return {
        success: false,
        data: [],
        error: result.message || 'Invalid response format'
      };
    }

    return {
      success: false,
      data: [],
      error: 'No completion generated'
    };

  } catch (error) {
    console.error('AI补全请求失败:', error);
    return {
      success: false,
      data: [],
      error: error instanceof Error ? error.message : 'Unknown error'
    };
  }
}

/**
 * 检查补全内容是否有效
 * @param text 补全文本
 * @returns 是否有效
 */
function isValidCompletion(text: string): boolean {
  if (!text) {
    return false;
  }

  // 过滤掉明显的错误补全
  if (text.includes('<|fim_') || text.includes('|>')) {
    return false;
  }
  if (text == '0') {
    return false;
  }

  // 允许所有其他内容，包括只包含空格、换行符的内容
  // 因为这些可能是有效的代码格式
  return true;
}

/**
 * 使用AI为代码添加注释（流式输出）
 * @param request 注释请求参数
 * @param onStreamComment 流式注释回调函数
 * @returns 注释结果
 */
export async function getAICodeComments(
  request: AICommentServiceRequest,
  onStreamComment?: (comment: { lineNumber: number; comment: string }) => void
): Promise<AICommentServiceResponse> {
  try {
    const { code, language } = request;

    console.log('AI代码注释请求参数:', { language, codeLength: code.length });
    // 为代码添加行号标记，便于AI准确定位
    const codeLines = code.split('\n');

    console.log('发送AI注释请求...');

    // 构建请求URL和数据
    const url = 'http://127.0.0.1:8080/api/ai/comments/stream';
    const requestData = {
      "code": code,
      "language": language || "c++"
    };

    console.log('请求URL:', url);
    console.log('请求数据:', requestData);

    // 发送POST请求
    const myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    
    const raw = JSON.stringify(requestData);
    
    const requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: raw,
      redirect: 'follow' as RequestRedirect
    };
    
    const response = await fetch(url, requestOptions);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 处理流式响应
    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('无法获取响应流');
    }

    const decoder = new TextDecoder();
    let buffer = "";
    let jsonBuffer = ""; // 专门用于累积JSON片段
    const comments: { lineNumber: number; comment: string }[] = [];
    console.log("AI注释流式输出开始：");

    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;
        console.log('接收到数据块:', chunk);

        // 处理Server-Sent Events格式的数据
        const lines = buffer.split('\n');
        buffer = lines.pop() || ''; // 保留最后一行（可能不完整）

        for (const line of lines) {
          const trimmedLine = line.trim();
          
          // 处理以'data:'开头的SSE数据
          if (trimmedLine.startsWith('data:')) {
            const dataContent = trimmedLine.substring(5).trim(); // 移除'data:'前缀
            
            // 累积所有data内容到jsonBuffer
            jsonBuffer += dataContent;
            
            // 检查是否形成了完整的JSON对象
            const completeJSON = tryExtractCompleteJSON(jsonBuffer);
            if (completeJSON) {
              try {
                const commentObj = JSON.parse(completeJSON.json);
                if (commentObj.lineNumber && commentObj.comment &&
                  typeof commentObj.lineNumber === 'number' &&
                  typeof commentObj.comment === 'string' &&
                  commentObj.lineNumber > 0 && commentObj.lineNumber <= codeLines.length) {

                  console.log('解析到注释:', commentObj);
                  comments.push(commentObj);

                  // 立即回调，实现流式注释
                  if (onStreamComment) {
                    onStreamComment(commentObj);
                  }
                }
                
                // 移除已处理的JSON，保留剩余部分
                jsonBuffer = completeJSON.remaining;
              } catch (parseError) {
                console.warn('解析累积JSON失败:', completeJSON.json, parseError);
                // 解析失败时清空buffer重新开始
                jsonBuffer = "";
              }
            }
          }
        }
      }
    } finally {
      reader.releaseLock();
    }

    // 处理最后的缓冲区内容
    if (jsonBuffer.trim()) {
      const finalJSON = tryExtractCompleteJSON(jsonBuffer);
      if (finalJSON) {
        try {
          const commentObj = JSON.parse(finalJSON.json);
          if (commentObj.lineNumber && commentObj.comment &&
            typeof commentObj.lineNumber === 'number' &&
            typeof commentObj.comment === 'string' &&
            commentObj.lineNumber > 0 && commentObj.lineNumber <= codeLines.length) {

            console.log('解析到最后注释:', commentObj);
            comments.push(commentObj);

            if (onStreamComment) {
              onStreamComment(commentObj);
            }
          }
        } catch (parseError) {
          console.warn('解析最终JSON失败:', finalJSON.json, parseError);
        }
      }
    }

    console.log(`\n流式解析完成，共获得 ${comments.length} 条注释`);

    return {
      success: true,
      data: comments
    };

  } catch (error) {
    console.error('AI代码注释请求失败:', error);
    return {
      success: false,
      data: [],
      error: error instanceof Error ? error.message : 'Unknown error'
    };
  }
}

/**
 * 从累积的JSON片段中提取完整的JSON对象
 * @param buffer 累积的JSON片段
 * @returns 提取结果，包含完整JSON和剩余内容
 */
function tryExtractCompleteJSON(buffer: string): { json: string; remaining: string } | null {
  // 清理buffer，移除多余的空格和换行
  const cleanBuffer = buffer.replace(/\s+/g, ' ').trim();
  
  // 寻找完整的JSON对象
  let braceCount = 0;
  let startIndex = -1;
  let endIndex = -1;
  
  for (let i = 0; i < cleanBuffer.length; i++) {
    const char = cleanBuffer[i];
    
    if (char === '{') {
      if (startIndex === -1) {
        startIndex = i;
      }
      braceCount++;
    } else if (char === '}') {
      braceCount--;
      
      if (braceCount === 0 && startIndex !== -1) {
        endIndex = i;
        break;
      }
    }
  }
  
  // 如果找到完整的JSON对象
  if (startIndex !== -1 && endIndex !== -1) {
    const jsonStr = cleanBuffer.substring(startIndex, endIndex + 1);
    const remaining = cleanBuffer.substring(endIndex + 1);
    
    return {
      json: jsonStr,
      remaining: remaining
    };
  }
  
  return null;
}

export default aiApi;